package org.thesis.secutity;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;

import android.util.Base64;
import android.util.Log;
public class DEScontrol 
{
	SecretKey key;
	Cipher Cip;
	String tag = "DEScontrol";
	public DEScontrol(SecretKey key) {
		super();
		this.key = key;
	}
	public String Encrypt(String input)
    {
        try
        {
            Cip = Cipher.getInstance("DES");
            Cip.init(Cipher.ENCRYPT_MODE, key);
            byte[] utf8 = input.getBytes("UTF8");
            byte[] enc = Cip.doFinal(utf8);
            return Base64.encodeToString(enc, 0);

        }
        catch(Exception e)
        {
            return null;

        }
    }

    public String Decrypt(String input)
    {
        try
        {
            Cip = Cipher.getInstance("DES");
            Cip.init(Cipher.DECRYPT_MODE, key);
            byte[] dec = Base64.decode(input, 0);
            // Decrypt
            byte[] utf8 = Cip.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");
        }
        catch(Exception e)
        {
            return null;
        }
    }
    
    public void encryptFile(String pathFileIn,String pathFileOut)
    {
        //File output = null;
        try
        {
            Cip = Cipher.getInstance("DES");
            Cip.init(Cipher.ENCRYPT_MODE, key);
            FileInputStream fis = new FileInputStream(pathFileIn);
            CipherOutputStream cos = new CipherOutputStream(new FileOutputStream(pathFileOut), Cip);
            copy(fis, cos);
            cos.close();


        }
        catch(Exception e)
        {
                Log.v(tag, "loi ma hoa file"+e.toString());
        }
      //  return output;

    }

    public void decryptFile(String pathFileIn,String pathFileOut)
    {
        try
        {
            Cip = Cipher.getInstance("DES");
            Cip.init(Cipher.DECRYPT_MODE, key);
            CipherInputStream cis = new CipherInputStream(new FileInputStream(pathFileIn), Cip);
            FileOutputStream fos = new FileOutputStream(pathFileOut);
            copy(cis, fos);
            cis.close();
            fos.close();
        }
        catch(Exception e)
        {
                Log.v(tag, "loi giai ma file "+e.toString());
        }
    }
    private void copy(InputStream is, OutputStream os) throws IOException {
		int i;
		byte[] b = new byte[1024];
		while((i=is.read(b))!=-1) {
			os.write(b, 0, i);
		}
	}
}
